#理解Harris角点检测的概念
#使用函数cv2.cornerHarris()，cv2.cornerSubPix()
import cv2
import numpy as np



img = cv2.imread("./qipan.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
#图像转换为float32

dst = cv2.cornerHarris(gray,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv2.dilate(dst, None)#图像膨胀

# Threshold for an optimal value, it may vary depending on the image.
#print(dst)
#img[dst>0.00000001*dst.max()]=[0,0,255] #可以试试这个参数，角点被标记的多余了一些
img[dst>0.01*dst.max()]=[0,0,255]#角点位置用红色标记
#这里的打分值以大于0.01×dst中最大值为边界

cv2.imshow('cornerHarris',img)
if cv2.waitKey(0) & 0xff == 27:
    cv2.destroyAllWindows()


ret, dst = cv2.threshold(dst,0.01*dst.max(),255,0)
dst = np.uint8(dst)

#找到重心
ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)

#定义迭代次数
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
corners = cv2.cornerSubPix(gray,np.float32(centroids),(5,5),(-1,-1),criteria)
#返回角点
#绘制
res = np.hstack((centroids,corners))
res = np.int0(res)
img[res[:,1],res[:,0]]=[0,0,255]
img[res[:,3],res[:,2]] = [0,255,0]

cv2.imshow('cornerSubPix',img)
cv2.waitKey(0)
cv2.destroyAllWindows()